package com.atguigu.gulimail.product.web;

import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model){
        //TODO 查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories", categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //获取分布式锁，只要锁名一样，就是同一把锁
        /*
        lock.lock()，不带参数
        1)redisson有锁的自动续期功能，如果业务超长，运行期间会自动给锁续上新的30s（默认）
        2）加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁也会默认在30s以后自动删除

         */
        RLock lock = redisson.getLock("my-lock");
        //加锁, 阻塞式等待
        lock.lock(10, TimeUnit.SECONDS); //10s自动解锁,自动解锁时间一定要大于业务执行时间
        //上述加锁方法不支持自动续期
        //如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //如果我们未传递锁的超时时间，就使用30*1000(看门狗的默认时间),只要占锁成功，就会启动一个定时任务
        //重新给锁设置过期时间，新的过期时间就是看门狗的默认时间
        //每隔 看门狗/3（10s） 的时间会重新设置锁的过期时间

        //最佳实战
        //lock.lock(30, TimeUnit.SECONDS)：省去了整个续期操作，手动解锁
        try{
            System.out.println("加锁成功，执行业务..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }
        finally {
            //解锁，假设解锁代码因为断电等原因没有运行，也不会死锁
            System.out.println("解锁..."+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue(){
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        rLock.lock();
        try {
            //改数据加写锁
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", s);
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue(){
        String s = "";
        //加读锁
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            s = redisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return s;
    }
}
